JBB_USERNAME_KEY = 'javablackbelt.Person.Field.USERNAME';

function elt(id) {
    return document.getElementById(id);
}


function log(s) {
    if (dump) dump(s);
    
    // todo: introduce a generic logging function
}

/**
 * Request the OWNER and OWNER's JBB username.
 */
function onLoad() {
    log('Preparing request...');
    var req = opensocial.newDataRequest();

    requestOwnerAndState(req)
}


function updateJbbUsername() {
    log('updateJbbUsername()');
    var req = opensocial.newDataRequest();

    var username = document.getElementById('jbb_username').value;

    req.add(req.newUpdatePersonAppDataRequest('VIEWER', JBB_USERNAME_KEY, username));
    postActivity("New JBB User!", "The guy just added the JBB username!");
    elt('belt_image').src = "http://jbb-belt-os.appspot.com/static/ajax-loader.gif";

    requestOwnerAndState(req);
}

function requestOwnerAndState(req) {
    req.add(req.newFetchPersonRequest('OWNER'), 'get_owner');
    req.add(req.newFetchPersonRequest('VIEWER'), 'get_viewer');
    req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.PersonId.OWNER, JBB_USERNAME_KEY), 'jbb_data');

    log('Sending request...');
    req.send(response);
}

function response(dataResponse) {
    log('Received response');
    log('Received response: ' + gadgets.json.stringify(dataResponse.get('jbb_data').getData()));
    var owner = dataResponse.get('get_owner').getData();
    var viewer = dataResponse.get('get_viewer').getData();
    var data = dataResponse.get('jbb_data').getData();

    var name = data[owner.getId()][JBB_USERNAME_KEY];

    elt('editor').style.display = viewer.getId() == owner.getId() ? 'block' : 'none';
    elt('viewer').style.display = viewer.getId() == owner.getId() ? 'none' : 'block';
    elt('jbb_username').value = name;
    elt('jbb_username_view').innerHTML = name;

    var prefs = new _IG_Prefs();
    updateBelt(prefs.getString("jbb_belt_size"), name);
}

function updateBelt(size, name) {
    gadgets.io.makeRequest('http://www.JavaBlackBelt.com/RemoteUserBelt.wwa?userNames=' + name +
                           '&size=' + size, jbb_callback);
}

function onActivityPosted(data) {
    if (data.hadError()) {
        alert("There was a problem: " + data.getErrorMessage());
    } else {
        log("The activity was posted successfully.");
    }
}


function postActivity(title, body) {
    var data = {};
    data[opensocial.Activity.Field.TITLE] = title;
    data[opensocial.Activity.Field.BODY] = body;
    var activity = opensocial.newActivity(data);
    opensocial.requestCreateActivity(
            activity,
            opensocial.CreateActivityPriority.HIGH,
            onActivityPosted
            );
}


function jbb_callback(data) {
    var re = /src\=\"([^"]*)\"/;
    var m = re.exec(data.data);
    elt('belt_image').src = m[1];
}
